package com.shenzhen.horselive;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentPagerAdapter;
import androidx.viewpager.widget.PagerAdapter;
import androidx.viewpager.widget.ViewPager;

import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.flqy.baselibrary.utils.VersionUtils;
import com.gyf.immersionbar.ImmersionBar;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.mozillaonline.providers.DownloadManager;
import com.shenzhen.horselive.adapter.HomeViewPageAdapter;
import com.shenzhen.horselive.adapter.MyViewPageAdapter;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.ActivityCollector;
import com.shenzhen.horselive.base.BaseActivity;
import com.shenzhen.horselive.beans.HandOutBean;
import com.shenzhen.horselive.beans.TokenOverTimeMessage;
import com.shenzhen.horselive.beans.UpdateBean;
import com.shenzhen.horselive.common.utils.Utils;
import com.shenzhen.horselive.databinding.ActivityMainBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.ViewObserver;
import com.shenzhen.horselive.ui.activity.LoginActivity;
import com.shenzhen.horselive.ui.dialog.UpdateDialog;
import com.shenzhen.horselive.ui.fragment.HongBaoFragment;
import com.shenzhen.horselive.ui.fragment.LianTongFragment;
import com.shenzhen.horselive.ui.fragment.LianTongTestFragment;
import com.shenzhen.horselive.ui.fragment.MeFragment;
import com.shenzhen.horselive.ui.fragment.WealthFragment;
import com.shenzhen.horselive.utils.DialogManager;
import com.shenzhen.horselive.widget.ContentViewHolder;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

public class MainActivity extends BaseActivity {
    ActivityMainBinding  binding;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        ImmersionBar.with(this)
                .statusBarDarkFont(true)
                .init();
        setContentView(binding.getRoot());
        initViews();
        //版本更新
        checkVersion();
        //设置别名
        JPushInterface.setAlias(getContext(), User.get().getMyInfo().getId() + "", new TagAliasCallback() {
            @Override
            public void gotResult(int i, String s, Set<String> set) {

            }
        });
    }

    //版本跟新
    private void checkVersion() {
        //0是安卓
        ApiFactory.getApiService().update("0")
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new ViewObserver<UpdateBean>(this) {
                    @Override
                    protected void onNextInActive(UpdateBean updateBean) {
                        if (updateBean.isSuccess())
                        {
                            int  nowVersion = VersionUtils.getCurrentVersionCode(getContext());
                            //版本低于网站版本就下载
                            if (nowVersion<Integer.parseInt(updateBean.getData().getVersionNumber()))
                            {
                                //需要版本更新
                                String  verSionName = "V"+VersionUtils.getCurrentVersion(getContext());
                                String   notice = updateBean.getData().getVersionContent();
                                String  downUrl = updateBean.getData().getDownloadAddress();
                                boolean  isFouce = updateBean.getData().getIsForceUpdate()==1?true:false;
                                DialogManager.getInstance().showUpdateDialog(getContext(), verSionName, notice
                                        , new UpdateDialog.OnUpdateClick() {
                                            @Override
                                            public void onClick() {
                                                // 下载安装
                                                AllenVersionChecker
                                                        .getInstance()
                                                        .downloadOnly(
                                                                UIData.create()
                                                                        .setDownloadUrl(downUrl)
                                                        )
                                                        //直接下载，不弹窗
                                                        .setDirectDownload(true)
                                                        .executeMission(getContext());


                                            }
                                        }, isFouce);

                            }

                        }
                    }
                });
    }

    //初始化
    private void initViews() {
//        List<Fragment>  list = new ArrayList<>();
//        list.add(LianTongTestFragment.newInstance());
//        list.add(HongBaoFragment.newInstance());
//        list.add(WealthFragment.newInstance());
//        list.add(new MeFragment());
//        MyViewPageAdapter  pageAdapter =  new MyViewPageAdapter(getSupportFragmentManager(),list);
        HomeViewPageAdapter  homeViewPageAdapter
                =new HomeViewPageAdapter(getSupportFragmentManager(), FragmentPagerAdapter.BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT);
        binding.viewpage.setScroll(false);
        binding.viewpage.setAdapter(homeViewPageAdapter);
        binding.viewpage.setOffscreenPageLimit(homeViewPageAdapter.getCount());
        binding.tabs.setupWithViewPager(binding.viewpage);
        binding.viewpage.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
               switch (position)
               {
                   case 0:
                       ImmersionBar.with(MainActivity.this)
                               .reset()
                               .statusBarDarkFont(true)
                               .init();
                       break;
                   case 1:
                       ImmersionBar.with(MainActivity.this)
                               .fitsSystemWindows(true)
                               .statusBarColor(R.color.white)
                               .statusBarDarkFont(true)
                               .init();
                       break;
                   case 2:
                   case 3:
                       ImmersionBar.with(MainActivity.this)
                               .fitsSystemWindows(true)
                               .statusBarColor(R.color.red_common)
                               .statusBarDarkFont(false)
                               .init();
                       break;
               }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //初始化导航栏
        int[]  mipmaps = {R.drawable.main_tab1,R.drawable.main_tab2,R.drawable.main_tab3,R.drawable.main_tab4};
       String[]  text= {"联通","红包","财富","我的"};
        for (int i = 0; i <binding.tabs.getTabCount() ; i++) {
            View  view = LayoutInflater.from(this)
                    .inflate(R.layout.tab_item,null);
            TextView  textView = view.findViewById(R.id.tv_tab);
            ImageView imageView =view.findViewById(R.id.img_tab);
            textView.setText(text[i]);
            imageView.setImageResource(mipmaps[i]);
            binding.tabs.getTabAt(i).setCustomView(view);
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //取消所有的下载任务,放置内存泄漏
        AllenVersionChecker.getInstance().cancelAllMission();
    }
    //token过期
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(TokenOverTimeMessage event) {
        if (event.getCode()==0)
        {
            if (!ActivityCollector.isActivityExist(LoginActivity.class))
            {
                ActivityCollector.removeAllActivity();
                //打开微信登录的页面
                startActivity(new Intent(getContext(),LoginActivity.class));
            }
        }
    }

}
